﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;


namespace PRT {

    public enum IBLDebug {
        None,
        ShowDirector
    }

    // IBL的Probe
    public class IBLProbe : MonoBehaviour, IProbe {
        public Cubemap m_DiffuseCubeMap = null;
        public Shader m_DiffuseShader = null;
        public int m_CubeMapSize = 512;
        public IBLDebug m_Debug = IBLDebug.None;

#if UNITY_EDITOR

        public void GenerateCubeMap(bool isMustInit = false) {
            if (!isMustInit && m_DiffuseCubeMap != null)
                return;
            m_DiffuseCubeMap = new Cubemap(m_CubeMapSize, TextureFormat.RGB24, false);
            m_DiffuseCubeMap = new Cubemap(m_CubeMapSize, TextureFormat.RGB24, false);
            m_DiffuseCubeMap.filterMode = FilterMode.Bilinear;
            m_DiffuseCubeMap.Apply();
        }

        void SaveCubeMap() {
            const string diffPath = "Assets/Resources/IBL_Gen/diffuse.cubemap";
            Utils.SaveCubeMap(diffPath, m_DiffuseCubeMap);
        }

        public void GenerateIrrCubeMap(Camera cam) {

            if (m_DiffuseShader == null) {
                Debug.LogError("Diffuse Shader is not vaild~!");
                return;
            }

            var sceneRenderers = GameObject.FindObjectsOfType<MeshRenderer>();

            bool isHasSceneRenders = sceneRenderers != null && sceneRenderers.Length > 0;
           

            cam.transform.position = this.transform.position;


            GenerateCubeMap(true);

            Dictionary<long, Shader> m_OriShaders = new Dictionary<long, Shader>();
            if (isHasSceneRenders)
                Utils.CollectRendersShaders(sceneRenderers, m_OriShaders);

            try {
                if (isHasSceneRenders)
                    Utils.ChangeRendersShader(sceneRenderers, m_DiffuseShader);
                cam.RenderToCubemap(m_DiffuseCubeMap);
            } finally {
                if (isHasSceneRenders)
                    Utils.ChangeRendersShaders(sceneRenderers, m_OriShaders);
            }

            SaveCubeMap();
        }

#endif
    }

}
